package cn.spiral.core.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.spiral.core.constant.Constant;
import cn.spiral.core.permisson.PermissonCheck;
import cn.spiral.user.entity.User;

public class LoginFilter implements Filter{

	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request=(HttpServletRequest) arg0;
		HttpServletResponse response=(HttpServletResponse) arg1;
		//从reqest中获得请求地址
		String uri=request.getRequestURI();
		
		//判断是否为登陆相关的请求，不是则进行进一步处理
		if(!uri.contains("sys/login_")){
			
			//判断用户是否已经登陆
			if(request.getSession().getAttribute(Constant.USER)!=null){
				//用户登陆过了,如果要访问纳税服务子系统，则进行权限判断
				if(uri.contains("/nsfw/")){
					User user=(User)request.getSession().getAttribute(Constant.USER);
					//获得spring容器，并从spring容器中获得单例的权限验证类
					//因为过滤器使用频繁，不能每次使用都实例化一个权限验证类
					WebApplicationContext applicationContext=WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
					PermissonCheck pc=(PermissonCheck) applicationContext.getBean("permissionCheck");
					if(pc.isAccessible(user, "nsfw")){
							chain.doFilter(request, response);
					}else {
						//跳转到没有权限提示页面
						response.sendRedirect(request.getContextPath() + "/sys/login_toNoPermissionUI.action");
					}
				}else{
					//放行
					chain.doFilter(request, response);
				}
				
			}else{
				//没有登陆将跳转到登陆页面
				response.sendRedirect(request.getContextPath()+"/sys//sys/login_toLoginUI.action");
			}
		}else{
			//登陆相关请求直接放行
			chain.doFilter(request, response);
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
	}

	
}
